package aar.test.tessocr;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.android.OpenCVLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.adapter.CompanySearchInfoAdapter;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CompanySearchModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.SiteDispatchModel;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.tessOcrUtil.CameraView2;
import aar.test.tessocr.tessOcrUtil.ListViewForScrollView;
import aar.test.tessocr.tessOcrUtil.RecycledImageView;
import aar.test.tessocr.tessOcrUtil.TesseractUtil;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.LogUtils;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.TipHelper;
import aar.test.tessocr.utils.UnzipAssets;
import aar.test.tessocr.utils.Urls;
import clx.tessocr.ocreng.R;
import lib_zxing.activity.CaptureActivity;
import lib_zxing.activity.CaptureFragment;
import lib_zxing.activity.CodeUtils;
import okgo.OkGo;
import okgo.callback.StringCallback;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;

public class SiteDispatchActivity extends BaseActivity {

    private Context mContext;

    private DisplayMetrics dm;

    private LinearLayout left_layout;

    private TextView grid_open, grid_confirm, grid_continue;


    private String text;


    private FrameLayout fl_zxing_container;

    private TextView grid_small, grid_middle, grid_big;

    private EditText san_order_id;

    private EditText san_number_phone;

    private int grid_type = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_site_dispatch);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        iniLoadOpenCV();

        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        } else {

            unZipAssset();
        }


    }


    private void initView() {

        CaptureFragment captureFragment = CaptureFragment.newInstance(1);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
        captureFragment.setCameraInitCallBack(new CaptureFragment.CameraInitCallBack() {
            @Override
            public void callBack(Exception e) {
                if (e == null) {

                } else {
                    Log.e("TAG", "callBack: ", e);
                }
            }
        });

        grid_open = findViewById(R.id.grid_open);

        grid_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridOpen(1);
            }
        });

        grid_confirm = findViewById(R.id.grid_confirm);

        grid_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridConfirem();
            }
        });

        grid_continue = findViewById(R.id.grid_continue);

        grid_continue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                san_order_id.setText("");
                san_number_phone.setText("");

                grid_small.setBackgroundColor(getResources().getColor(R.color.title_background_color));
                grid_middle.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                grid_big.setBackgroundColor(getResources().getColor(R.color.colorWhite));


                grid_small.setTextColor(getResources().getColor(R.color.title_bottom_color));
                grid_middle.setTextColor(getResources().getColor(R.color.app_background_color));
                grid_big.setTextColor(getResources().getColor(R.color.app_background_color));

                BaseApplication.getIntance().setmSiteDispatchModel(null);
            }
        });


        san_order_id = findViewById(R.id.san_order_id);
        san_number_phone = findViewById(R.id.san_number_phone);


        left_layout = findViewById(R.id.left_layout);
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        fl_zxing_container = findViewById(R.id.fl_zxing_container);

        grid_small = findViewById(R.id.grid_small);
        grid_small.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                grid_type = 3;

                grid_small.setBackgroundColor(getResources().getColor(R.color.title_background_color));
                grid_middle.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                grid_big.setBackgroundColor(getResources().getColor(R.color.colorWhite));


                grid_small.setTextColor(getResources().getColor(R.color.title_bottom_color));
                grid_middle.setTextColor(getResources().getColor(R.color.app_background_color));
                grid_big.setTextColor(getResources().getColor(R.color.app_background_color));
            }
        });
        grid_middle = findViewById(R.id.grid_middle);
        grid_middle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                grid_type = 1;
                grid_small.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                grid_middle.setBackgroundColor(getResources().getColor(R.color.title_background_color));
                grid_big.setBackgroundColor(getResources().getColor(R.color.colorWhite));

                grid_small.setTextColor(getResources().getColor(R.color.app_background_color));
                grid_middle.setTextColor(getResources().getColor(R.color.title_bottom_color));
                grid_big.setTextColor(getResources().getColor(R.color.app_background_color));

            }
        });
        grid_big = findViewById(R.id.grid_big);
        grid_big.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                grid_type = 2;
                grid_small.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                grid_middle.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                grid_big.setBackgroundColor(getResources().getColor(R.color.title_background_color));

                grid_small.setTextColor(getResources().getColor(R.color.app_background_color));
                grid_middle.setTextColor(getResources().getColor(R.color.app_background_color));
                grid_big.setTextColor(getResources().getColor(R.color.title_bottom_color));
            }
        });


    }


    private void iniLoadOpenCV() {
        boolean success = OpenCVLoader.initDebug();
        if (success) {
            Log.e("MainActivity", "OpenCV Library loaded...");
        } else {
            Toast.makeText(this.getApplicationContext(), "could not load opencv lib...", Toast.LENGTH_LONG).show();
        }
    }


    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();
                    unZipAssset();
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(SiteDispatchActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(SiteDispatchActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };


    private void unZipAssset() {

        prepareSdPath();

        prepareSdPath2();

        try {

            File file = new File(TesseractUtil.TESSBASE_PATH_DOWN);

            File file2 = new File(TesseractUtil.TESSBASE_PATH_DOWN + "/normal.traineddata");

            if (!file.exists() || (file.exists() && !file2.exists())) {
                new Thread() {
                    public void run() {
                        //在新线程中以同名覆盖方式解压
                        UnzipAssets.unZip(SiteDispatchActivity.this, ConstantPara.UN_ZIP_ASSET_NAME, TesseractUtil.TESSBASE_PATH, true);
                    }
                }.start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath() {

        try {

            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRootThumbnail = new File(TesseractUtil.TESSBASE_PATH);
                if (!sPathRootThumbnail.exists()) {
                    sPathRootThumbnail.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath2() {

        String RootFilePath = Environment.getExternalStorageDirectory() + "/DCIM/";

        String sSubDir = "normal";
//        String RootFilePath=  Environment.getExternalStorageDirectory() + "/Download/";

        try {


            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRoot = new File(RootFilePath);
                if (!sPathRoot.exists()) {
                    sPathRoot.mkdirs();
                }
                File sPathVid = new File(RootFilePath + sSubDir);
                LogUtils.e("MainActivity", "sPathVid.exists()==" + sPathVid.exists());
                if (!sPathVid.exists()) {
                    sPathVid.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public int getStatusBarHeight() {
        int result1 = 0;
        LogUtils.e("getStatusBarHeight", "result1.result1()==" + result1);
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result1 = getResources().getDimensionPixelSize(resourceId);
        }

        LogUtils.e("getStatusBarHeight", "result1.result1()==" + result1);
        return result1;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();


        OkGo.getInstance().cancelTag(this);
    }


    private String preStatus = "-1", curStatus = "-1";


    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result, final int type) {

//            if(type==1){
//                Toast.makeText(SiteDispatchActivity.this, "bar      "+result, Toast.LENGTH_LONG).show();
//            }else  if(type==2){
//                Toast.makeText(SiteDispatchActivity.this, "ph       "+result, Toast.LENGTH_LONG).show();
//            }
            final String res = result;
            if (!TextUtils.isEmpty(res)) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (type == 1) {
                            san_order_id.setText(res);
                        } else if (type == 2) {

                            san_number_phone.setText(res);
                        }


                    }
                });
            }

        }

        @Override
        public void onAnalyzeFailed() {

            Toast.makeText(SiteDispatchActivity.this, "没有识别到信息", Toast.LENGTH_LONG).show();
        }
    };

//    private void gridOpen(int pos) {
//
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("cabinetId", "3");
//        map.put("gridType", grid_type + "");
//
//        Gson gg = new Gson();
//        String json = gg.toJson(map);
//
//        RequestBody body = RequestBody.create(JSON, json);
//        OkGo.<LzyResponse<SiteDispatchModel>>post(Urls.URL_XIANCHANG)//
//                .tag(this)//
//                .upRequestBody(body)
//                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
//                .execute(new DialogCallback<LzyResponse<SiteDispatchModel>>(SiteDispatchActivity.this) {
//                    @Override
//                    public void onSuccess(Response<LzyResponse<SiteDispatchModel>> response) {
//
//
//                        Log.e("MainActivity", "onSuccess-----logout---------------" + response.body().data);
//
//                        BaseApplication.getIntance().setmSiteDispatchModel(response.body().data);
//                        if(null!=response&&null!=response.body()&&null!=response.body().msg){
//                            Toast.makeText(getApplicationContext(),response.body().msg,Toast.LENGTH_LONG).show();
//                        }
//
//                    }
//
//                    @Override
//                    public void onError(Response<LzyResponse<SiteDispatchModel>> response) {
//
//                        Log.e("MainActivity", "onError---------------------"+response.code());
//                        Log.e("MainActivity", "onError---------------------"+response.message());
//                        Log.e("MainActivity", "onError---------------------"+response.body());
//
//                        if(null!=response&&null!=response.body()&&null!=response.body().msg){
//                            Toast.makeText(getApplicationContext(),response.body().msg,Toast.LENGTH_LONG).show();
//                        }
//
//                    }
//                });
//
//
//    }


    private void gridOpen(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetId", "3");
        map.put("gridType", grid_type + "");

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_XIANCHANG)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                 String msg=jsonObject.getString("msg");
                                    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
                                }else if (TextUtils.equals(code, "100")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();

                                    String data=jsonObject.getString("data");

                                    if(!TextUtils.isEmpty(data)){
                                        JSONObject dataObject = new JSONObject(data);
                                       String cabinetgridid=dataObject.getString("cabinetgridid");
                                       String cabinetid=dataObject.getString("cabinetid");
                                        String gridnum=dataObject.getString("gridnum");
                                        String isuse=dataObject.getString("isuse");
                                       String currentpassword=dataObject.getString("currentpassword");
                                        String gridtype=dataObject.getString("gridtype");
                                        String sku=dataObject.getString("sku");
                                        String companyid=dataObject.getString("companyid");
                                        String orderid=dataObject.getString("orderid");
                                      String expresspassword=dataObject.getString("expresspassword");

                                        SiteDispatchModel siteDispatchModel=new SiteDispatchModel();
                                        siteDispatchModel.setCabinetgridid(cabinetgridid);
                                        siteDispatchModel.setCabinetid(cabinetid);
                                        siteDispatchModel.setCompanyid(companyid);
                                        siteDispatchModel.setCurrentpassword(currentpassword);
                                        siteDispatchModel.setExpresspassword(expresspassword);
                                        siteDispatchModel.setGridnum(gridnum);
                                        siteDispatchModel.setIsuse(isuse);
                                        siteDispatchModel.setOrderid(orderid);
                                        siteDispatchModel.setGridtype(gridtype);
                                        siteDispatchModel.setSku(sku);


                                        BaseApplication.getIntance().setmSiteDispatchModel(siteDispatchModel);


                                    }
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }


    private void gridConfirem() {

        if (null == BaseApplication.getIntance().getmSiteDispatchModel()) {
            Toast.makeText(SiteDispatchActivity.this, "没有柜子信息，请先开柜再确认！", Toast.LENGTH_LONG).show();
            return;
        }

        if (TextUtils.isEmpty(san_order_id.getText().toString())) {
            Toast.makeText(SiteDispatchActivity.this, "请输入运单号", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(san_number_phone.getText().toString())) {
            Toast.makeText(SiteDispatchActivity.this, "请输入电话号", Toast.LENGTH_LONG).show();
            return;
        }


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetGridId", BaseApplication.getIntance().getmSiteDispatchModel().getCabinetgridid());
        map.put("express", san_order_id.getText().toString());
        map.put("phone", san_number_phone.getText().toString());
        map.put("adminid", PrefUtils.getString(this, "userId", ""));

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse>post(Urls.URL_XIANCHANG_CONFIRM)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse>(SiteDispatchActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {


                        Log.e("MainActivity", "onSuccess-----logout---------------" + response.body().data);
                        if (null != response && null != response.body() && null != response.body().msg) {
                            Toast.makeText(getApplicationContext(), response.body().msg, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {

                        Log.e("MainActivity", "onError---------------------");
                        if (null != response && null != response.body() && null != response.body().msg) {
                            Toast.makeText(getApplicationContext(), response.body().msg, Toast.LENGTH_LONG).show();
                        }

                    }
                });


    }


}
